package org.dromara.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import org.dromara.app.domain.AppLoginUser;
import org.dromara.app.domain.AppSocialAuth;
import org.dromara.app.domain.vo.AppUserVo;
import org.dromara.app.service.AppLoginService;
import org.dromara.app.service.AppSocialAuthService;
import org.dromara.app.service.AppUserService;
import org.dromara.app.service.IAppAuthStrategy;
import org.dromara.common.core.domain.model.SocialLoginBody;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.social.config.properties.SocialProperties;
import org.dromara.common.social.utils.SocialUtils;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.web.domain.vo.LoginVo;
import org.springframework.stereotype.Service;

/**
 * App第三方登录认证策略
 *
 * @author ruoyi
 */
@Slf4j
@Service("app_social" + IAppAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class AppSocialAuthStrategy implements IAppAuthStrategy {

    private final SocialProperties socialProperties;
    private final AppUserService appUserService;
    private final AppLoginService appLoginService;
    private final AppSocialAuthService appSocialAuthService;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        SocialLoginBody loginBody = JsonUtils.parseObject(body, SocialLoginBody.class);
        ValidatorUtils.validate(loginBody);
        String source = loginBody.getSource();
        String socialCode = loginBody.getSocialCode();
        String socialState = loginBody.getSocialState();
        // 获取第三方登录信息
        AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
        AuthCallback callback = AuthCallback.builder()
                .code(socialCode)
                .state(socialState)
                .build();
        AuthResponse<AuthUser> response = authRequest.login(callback);
        if (!response.ok()) {
            throw new ServiceException(response.getMsg());
        }
        AuthUser authUserData = response.getData();

        AppUserVo user = loadUserBySocial(authUserData.getSource(), authUserData.getUuid());
        assert user != null;
        appLoginService.checkLogin(LoginType.PASSWORD, user.getUserName(), () -> ObjectUtil.isNull(user));
        // 构建App登录用户
        AppLoginUser loginUser = new AppLoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getUserName());
        loginUser.setUserType("app");

        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        return loginVo;
    }

    /**
     * 通过第三方信息查找用户
     */
    private AppUserVo loadUserBySocial(String source, String openId) {
        // 根据第三方平台信息查找绑定的App用户
        log.info("App端第三方登录查找用户，source: {}, openId: {}", source, openId);

        // 首先通过openId查找
        AppSocialAuth socialAuth = appSocialAuthService.queryByPlatformAndOpenId(source, openId);

        if (socialAuth != null && socialAuth.getUserId() != null) {
            // 找到绑定的用户，返回用户信息
            AppUserVo user = appUserService.queryById(socialAuth.getUserId());
            if (user != null) {
                log.info("通过openId找到绑定用户，userId: {}, userName: {}", user.getUserId(), user.getUserName());
                return user;
            }
        }

        log.warn("未找到与第三方账号绑定的App用户，source: {}, openId: {}", source, openId);
        return null;
    }

}